package entity

import (
	"center-platform/utils"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"sync"
	"time"
)

type User struct {
	Id        int    `json:"id" gorm:"primaryKey"`
	Name      string `json:"name"`
	Email     string `json:"email" binding:"required"`
	Password  string `json:"password" binding:"required"`
	Status    int    `json:"status" gorm:"default:1"`
	Salt      string `json:"salt" gorm:"size:10"`
	Avatar    string `json:"avatar"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (u *User) TableName() string {
	return "user"
}

type UserBasicInfoResponse struct {
	Id        int       `json:"id"`
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	Avatar    string    `json:"avatar"`
	Status    int       `json:"status"`
	CreatedAt time.Time `json:"created_at"`
}

type UserUpdate struct {
	Id     int    `json:"id" binding:"required"`
	Name   string `json:"name"`
	Email  string `json:"email"`
	Avatar string `json:"avatar"`
	Status int    `json:"status"`
}

var lock sync.Mutex

func (ubir *UserBasicInfoResponse) TableName() string {
	return "user"
}

func (ubir *UserBasicInfoResponse) BuildResponse(user *User) *UserBasicInfoResponse {
	return &UserBasicInfoResponse{
		Name:      user.Name,
		Email:     user.Email,
		Status:    user.Status,
		CreatedAt: user.CreatedAt,
	}
}

func (u *User) Login() User {
	fmt.Println("login")
	return User{
		Name:  u.Name,
		Email: u.Email,
	}
}
func (u *User) Register() error {
	salt := utils.RandomString(10)
	u.Salt = salt
	err, hashedPassword := utils.HashStr(u.Password + u.Salt)

	if err != nil {
		return err
	}
	u.Password = hashedPassword
	result := utils.DB.Create(u)
	if result.Error != nil {
		return result.Error
	}
	return nil
}
func (u *User) GetInfoById(id int) *UserBasicInfoResponse {
	var UserRes UserBasicInfoResponse
	err := utils.DB.Model(&User{}).Where("id = ?", id).Find(&UserRes)
	if errors.Is(err.Error, gorm.ErrRecordNotFound) || UserRes.Id == 0 {
		return nil
	}
	return &UserRes
}

func (u *User) GetInfoByPw(email string, password string) (error, *UserBasicInfoResponse) {
	var UserRes UserBasicInfoResponse
	result := utils.DB.Where("email = ? ", email).First(u)
	if u.Id == 0 || errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return errors.New("查询不到该用户"), &UserRes
	}
	if !utils.Compared(u.Password, password+u.Salt) {
		return errors.New("密码错误"), &UserRes
	}
	UserRes.Id = u.Id
	UserRes.Name = u.Name
	UserRes.Status = u.Status
	UserRes.Email = u.Email
	UserRes.CreatedAt = u.CreatedAt
	return nil, &UserRes
}

func (u *UserUpdate) Update(where interface{}, update map[string]interface{}, args ...interface{}) error {
	lock.Lock()
	err := utils.DB.Model(&User{}).Where(where, args...).Updates(update).Error
	if err != nil {
		return err
	}
	lock.Unlock()
	return nil
}
